<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use think\App;
use think\Exception;
use think\facade\View;
use app\common\model\Menu as MenuModel;
use think\response\Json;

class Menu extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\Menu';

    public function index(): string
    {
        View::assign('menus', (new MenuModel())->getMenu('', 2));
        return View::fetch();

    }

    public function edit($id = '', $pid = '', $uid = '')
    {
        try {
            $p_title = '';
            if ($pid) {
                $p_title = MenuModel::where('id', $pid)->value('title');
            }
            View::assign('p_title', $p_title);
            View::assign('info', MenuModel::where('id', $id)->find());
            return View::fetch();

        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }

    public function save($param = [], $model = false): Json
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'menu');
            if ($param['id']) {
                MenuModel::update($param);
            } else {
                $result = Builder::TableCache()->autoCM($param);
                if ($result['code'] != 1) {
                    return json(['code' => -1, 'msg' => $result['msg']]);
                }
                MenuModel::create($param);
            }
            return json(['code' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
    }

    public function updateStatus($key, $val, $id): Json
    {
        try {
            if ($val == 'true') $val = 1;
            if ($val == 'false') $val = 0;
            MenuModel::update([$key => $val], ['id' => $id]);
            return json(['code' => 1, 'msg' => '操作成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }
}
